package it.orma.iridehr.service;


import java.security.Security;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.util.HtmlUtils;

import com.lowagie.text.html.HtmlEncoder;

import it.orma.iridehr.controllers.form.admin.EmailJobForm;
import it.orma.iridehr.controllers.ricerca.NewsForm;
import it.orma.iridehr.email.config.EmailParameter;
import it.orma.iridehr.entities.DatiGenerali;
import it.orma.iridehr.entities.SchedaCandidato;
import it.orma.iridehr.jobs.InitializingCronTrigger;
import it.orma.iridehr.jobs.EmailTask;
import it.orma.iridehr.repository.NewsRepository;
import it.orma.iridehr.repository.RicercaRepository;


public class EmailService {
	
	@Autowired
	RicercaRepository ricercaRepository;
	
	@Autowired
	NewsRepository newsRepository;
	
	Map<String, String> emailConfigs;
		
	public Boolean sendEmail(NewsForm newsForm) throws Exception{
		SchedaCandidato sc = new SchedaCandidato();
		sc.setIdSchedaCandidato(Long.parseLong(newsForm.getIdCandidatoToNotify()));		
		DatiGenerali dg = ricercaRepository.caricaDatiGenerali(sc);
		sendEmail("smpt", emailConfigs.get("smtpServer"), 
				emailConfigs.get("smtpPort"), 
				emailConfigs.get("smtpUsername"), 
				emailConfigs.get("smtpPassword"), dg.getMail1(), 
				newsForm.getEmailHTML());
		newsRepository.inviaEmail(Long.parseLong(newsForm.getIdNewsToHandle()));
		if (newsForm.getHideNews().equals("true")){
			newsRepository.nascondiNews(Long.parseLong(newsForm.getIdNewsToHandle()));
		}
		return true;
	}
	
	public Boolean readEmail(NewsForm newsForm) throws Exception{
		SchedaCandidato sc = new SchedaCandidato();
		sc.setIdSchedaCandidato(Long.parseLong(newsForm.getIdCandidatoToNotify()));		
		DatiGenerali dg = ricercaRepository.caricaDatiGenerali(sc);
		sendEmail("smpt", emailConfigs.get("smtpServer"), 
				emailConfigs.get("smtpPort"), 
				emailConfigs.get("smtpUsername"), 
				emailConfigs.get("smtpPassword"), dg.getMail1(), 
				newsForm.getEmailHTML());
		newsRepository.inviaEmail(Long.parseLong(newsForm.getIdNewsToHandle()));
		if (newsForm.getHideNews().equals("true")){
			newsRepository.nascondiNews(Long.parseLong(newsForm.getIdNewsToHandle()));
		}
		return true;
	}
	
	 private Properties getImapServerProperties(String protocol, String host,
	            String port, String userName, String password) {
		
		 
		 
		 return null;
	 
	 }
	
	 private Properties getSmtpServerProperties(String protocol, String host,
	            String port, String userName, String password) {

	        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 
	        Properties props = System.getProperties();
	        props.put("mail.smtp.host", host);
	        props.put("mail.smtp.socketFactory.port", port); //587
	        props.setProperty("mail.smtp.user", userName);
	        props.setProperty("mail.smtp.password", password);
	        props.put("mail.smtp.auth","true");
	        props.setProperty("mail.smtp.ssl.enable", "false");
	        props.put("mail.smtp.port", port); //465
	        props.put("mail.smtp.starttls.enable", "true");
	        props.put("mail.transport.protocol","smtp");
	        props.put("mail.smtp.ssl.trust", "*");
	       
	        return props;
	    }
	 

	    public void sendEmail(String protocol, String host, String port,
	            final String userName, final String password,final String recipient,final String content) throws Exception {
	        Properties properties = getSmtpServerProperties(protocol, host, port,userName,password);
	        Session session = Session.getInstance(properties,
	        new javax.mail.Authenticator() {
	            protected PasswordAuthentication getPasswordAuthentication() {
	                return new PasswordAuthentication(userName, password);
	            }
	        });
	 
	        try {
	        	Message  message = new MimeMessage (session);
				message.setFrom(new InternetAddress(emailConfigs.get("smtpBehalfUser"),"Orma hr"));
				message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
				message.setSubject("Conferma appuntamento Orma");
				message.setContent(HtmlUtils.htmlUnescape(content), "text/html; charset=utf-8");
	            Transport.send(message);
				
		        System.out.println("Sent message successfully....");
	            System.out.println("DONE");

	        } catch (Exception ex) {
	            System.out.println("Exception Occuered: " + ex.getMessage());
	            ex.printStackTrace();
	            throw new Exception("invio mail fallito");
	        }
	    }
	    public static final String escapeHTML(String s){
	    	   StringBuffer sb = new StringBuffer();
	    	   int n = s.length();
	    	   for (int i = 0; i < n; i++) {
	    	      char c = s.charAt(i);
	    	      switch (c) {	    	        
	    	         case '&': sb.append("&amp;"); break;
	    	         case 'à': sb.append("&agrave;");break;
	    	         case 'À': sb.append("&Agrave;");break;
	    	         case 'â': sb.append("&acirc;");break;
	    	         case 'Â': sb.append("&Acirc;");break;
	    	         case 'ä': sb.append("&auml;");break;
	    	         case 'Ä': sb.append("&Auml;");break;
	    	         case 'å': sb.append("&aring;");break;
	    	         case 'Å': sb.append("&Aring;");break;
	    	         case 'æ': sb.append("&aelig;");break;
	    	         case 'Æ': sb.append("&AElig;");break;
	    	         case 'ç': sb.append("&ccedil;");break;
	    	         case 'Ç': sb.append("&Ccedil;");break;
	    	         case 'é': sb.append("&eacute;");break;
	    	         case 'É': sb.append("&Eacute;");break;
	    	         case 'è': sb.append("&egrave;");break;
	    	         case 'È': sb.append("&Egrave;");break;
	    	         case 'ê': sb.append("&ecirc;");break;
	    	         case 'Ê': sb.append("&Ecirc;");break;
	    	         case 'ë': sb.append("&euml;");break;
	    	         case 'Ë': sb.append("&Euml;");break;
	    	         case 'ï': sb.append("&iuml;");break;
	    	         case 'Ï': sb.append("&Iuml;");break;
	    	         case 'ô': sb.append("&ocirc;");break;
	    	         case 'Ô': sb.append("&Ocirc;");break;
	    	         case 'ö': sb.append("&ouml;");break;
	    	         case 'Ö': sb.append("&Ouml;");break;
	    	         case 'ø': sb.append("&oslash;");break;
	    	         case 'Ø': sb.append("&Oslash;");break;
	    	         case 'ß': sb.append("&szlig;");break;
	    	         case 'ù': sb.append("&ugrave;");break;
	    	         case 'Ù': sb.append("&Ugrave;");break;         
	    	         case 'û': sb.append("&ucirc;");break;         
	    	         case 'Û': sb.append("&Ucirc;");break;
	    	         case 'ü': sb.append("&uuml;");break;
	    	         case 'Ü': sb.append("&Uuml;");break;
	    	         case '®': sb.append("&reg;");break;         
	    	         case '©': sb.append("&copy;");break;   
	    	         case '€': sb.append("&euro;"); break;

	    	         default:  sb.append(c); break;
	    	      }
	    	   }
	    	   return sb.toString();
	    	}

		public Map<String, String> getEmailConfigs() {
			return emailConfigs;
		}

		public void setEmailConfigs(Map<String, String> emailParameter) {
			this.emailConfigs = emailParameter;
		}

}
